package com.xbongbong.paas.help;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasStageEntity;
import com.xbongbong.paas.domain.entity.StageProcessEntity;
import com.xbongbong.paas.enums.StageTypeEnum;
import com.xbongbong.paas.model.StageProcessModel;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.service.stage.StageHandle;
import com.xbongbong.paas.service.stage.StageHandleFactory;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.parent.factory.StageExecuteFactory;
import com.xbongbong.parent.interfaces.StageExecuteHandle;
import com.xbongbong.pro.businesstage.pojo.dto.CommonJumpDTO;
import com.xbongbong.pro.enums.PaasStageEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @ClassName SaasStageHelp
 * @Description 阶段推进器相关help
 * @Author sunshaoxiang
 * @Date 2021/12/23 16:21
 * @Version 1.0
 **/
@Component
public class SaasStageHelp {

    private static final Logger LOG = LoggerFactory.getLogger(SaasStageHelp.class);

    @Resource
    private StageProcessModel stageProcessModel;
    @Resource
    private StageExecuteFactory stageExecuteFactory;
    @Resource
    private StageHandleFactory stageHandleFactory;

    /**
     * 新建编辑以及阶段跳转入老审批的后置操作
     * @param saasFormSaveDTO
     * @throws XbbException
     */
    public void stageJump(SaasFormSaveDTO saasFormSaveDTO, String stageAttr) throws XbbException{
        CommonJumpDTO commonJumpDTO = new CommonJumpDTO();
        boolean isNew = saasFormSaveDTO.getIsNew(); // 线索阶段变更消息推送 NullPointerException
        boolean isFromProcess = Objects.equals(saasFormSaveDTO.getIsFromProcess(), BasicConstant.ONE);
        try {
            String corpid = saasFormSaveDTO.getCorpid();
            JSONObject newData = saasFormSaveDTO.getNewData();
            JSONObject oldData = saasFormSaveDTO.getOldData();
            Integer businessType = saasFormSaveDTO.getBusinessType();
            PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
            Long dataId = newPaasFormDataEntity.getId();
            Long formId = newPaasFormDataEntity.getFormId();
            Long stageProcessId = FastJsonHelper.getLongOrDefaultFromFormData(newData, PaasStageEnum.STAGE_PROCESS_ID.getAttr(), BasicConstant.ZERO_LONG);
            StageProcessEntity stageProcessEntity;
            Long toStageId;
            Long fromStageId;
            PaasStageEntity toStageEntity;
            PaasStageEntity fromStageEntity;
            String toStageCode = FastJsonHelper.getStringOrDefaultFromFormData(newData, stageAttr, "");
            String fromStageCode = FastJsonHelper.getStringOrDefaultFromFormData(oldData, stageAttr, "");
            StageExecuteHandle stageExecute = stageExecuteFactory.getStageExecute(SaasMarkEnum.SAAS.getCode(), businessType);
            StageHandle stageHandle = stageHandleFactory.getStageHandle(SaasMarkEnum.SAAS.getCode(), businessType);
            //历史审批数据没有打入阶段id和阶段流程id,手动去拿
            if (Objects.equals(stageProcessId, BasicConstant.ZERO_LONG)) {
                stageProcessEntity = stageProcessModel.getByTransferVersion(corpid, formId, BasicConstant.ONE);
                toStageEntity = stageHandle.getByCode(corpid, formId, toStageCode);
                fromStageEntity =  stageHandle.getByCode(corpid, formId, fromStageCode);
            } else {
                stageProcessEntity = stageProcessModel.getByKey(stageProcessId, corpid);
                toStageId = FastJsonHelper.getLongOrDefaultFromFormData(newData, PaasStageEnum.STAGE_ID.getAttr(), BasicConstant.ZERO_LONG);
                fromStageId = FastJsonHelper.getLongOrDefaultFromFormData(oldData, PaasStageEnum.STAGE_ID.getAttr(), BasicConstant.ZERO_LONG);
                toStageEntity = stageHandle.getByKey(toStageId, corpid);
                fromStageEntity = stageHandle.getByKey(fromStageId, corpid);
            }
            commonJumpDTO.setIsImport(saasFormSaveDTO.getIsImport());
            commonJumpDTO.setPlatform(saasFormSaveDTO.getPlatform());
            commonJumpDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
            commonJumpDTO.setBusinessType(businessType);
            commonJumpDTO.setFormId(formId);
            commonJumpDTO.setDataId(dataId);
            commonJumpDTO.setCorpid(corpid);
            commonJumpDTO.setFromStageType(Objects.isNull(fromStageEntity) || isNew ? StageTypeEnum.START_STAGE.getType() : fromStageEntity.getType());
            commonJumpDTO.setUserId(isFromProcess ? saasFormSaveDTO.getProcessCreatorId() :  saasFormSaveDTO.getUserId());
            commonJumpDTO.setToStageType(toStageEntity.getType());
            commonJumpDTO.setFromStageEntity(Objects.isNull(fromStageEntity) || isNew ? null : fromStageEntity);
            commonJumpDTO.setToStageEntity(toStageEntity);
            commonJumpDTO.setStageProcessEntity(stageProcessEntity);
            commonJumpDTO.setStageAttr(stageAttr);
            commonJumpDTO.setFromApproval(BasicConstant.ONE);
            commonJumpDTO.setIsNew(isNew);
            commonJumpDTO.setFromOuterLink(saasFormSaveDTO.getFromOuterLink());
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                String wastage = saasFormSaveDTO.getNewPaasFormDataEntity().getData().getString(CustomerManagementEnum.WASTAGE.getAttr());
                if (StringUtils.isNotEmpty(wastage)) {
                    commonJumpDTO.setReasonId(Integer.valueOf(wastage));
                }
            }else if(Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
                JSONObject data = saasFormSaveDTO.getNewPaasFormDataEntity().getData();
                String reason = data.getString(ClueEnum.INVALID_REASON.getAttr());
                String memo = data.getString(ClueEnum.INVALID_MEMO.getAttr());
                if (StringUtils.isNotEmpty(reason)) {
                    commonJumpDTO.setReasonId(Integer.valueOf(reason));
                }
                if (StringUtils.isNotEmpty(memo)) {
                    commonJumpDTO.setMemo(memo);
                }
            }
            //调用详情页阶段跳转方法
            stageExecute.stageCommonJump(commonJumpDTO);
        } catch (XbbException e) {
            LOG.error("com.xbongbong.paas.help.SaasStageHelp.stageJump 日志打印：userid:{}，isFromProcess：{},commonJumpDTO:{}",commonJumpDTO.getUserId(),isFromProcess,commonJumpDTO);
            LOG.error("SaasStageHelp.stageCommonJump出错:", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

}
